package com.example.wishstar.view.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.widget.Toast;

import com.example.wishstar.MainActivity;
import com.example.wishstar.MyApplication;
import com.example.wishstar.R;
import com.example.wishstar.db.UserDao;
import com.example.wishstar.db.UserDatabase;
import com.example.wishstar.model.User;

import java.util.ArrayList;
import java.util.List;

public class WelcomeActivity extends AppCompatActivity {
    private User user;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);
        is_login();
        // 延迟3秒进入登录界面
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (user != null) {
                    Toast.makeText(WelcomeActivity.this, "欢迎" + user.getUser_mail(), Toast.LENGTH_SHORT).show();

                    Bundle bundle = new Bundle();
                    bundle.putInt("userId", user.user_id);
                    Intent intent = new Intent(WelcomeActivity.this, MainActivity.class);
                    intent.putExtras(bundle);
                    startActivity(intent);
                }
                else {
                    Intent intent = new Intent(WelcomeActivity.this, LoginActivity.class);
                    startActivity(intent);
                }
                WelcomeActivity.this.finish();
            }
        },1000 * 3);
    }

    public void is_login() {
        List<User> userList = new ArrayList<>();
        UserDatabase userDatabase = MyApplication.getUserDatabase();
        UserDao userDao = userDatabase.userDao();
        new Thread(new Runnable() {
            @Override
            public void run() {
                userList.addAll(userDao.getUserByState(1));
                if (userList.size() > 0) {
                    user = userList.get(0);
                }
                else {
                    user = null;
                }
            }
        }).start();
    }
}